<template>
  <div style="background-color: white">
    <div
      class="status-info mb20"
      :class="{ green: _detail.data?.status === 2, orange: _detail.data?.status === 4, red: _detail.data?.status === 3 }"
      v-if="[2, 3, 4].includes(_detail.data?.status)"
    >
      <el-icon>
        <WarningFilled />
      </el-icon>
      <el-tag v-if="_detail.data?.status === 2" class="ml10 mr10" :type="'success'" effect="light" size="small"> 已通过 </el-tag>
      <el-tag v-if="_detail.data?.status === 3" class="ml10 mr10" :type="'danger'" effect="dark" size="small"> 已拒绝 </el-tag>
      <el-tag v-if="_detail.data?.status === 4" class="ml10 mr10" :type="'warning'" effect="light" size="small"> 审核中 </el-tag>
      <p class="text-over">{{ _detail.data?.processRemark || "-" }}</p>
    </div>
    <div v-if="!isEditChange" class="top pb0 pt10">
      <div class="total-wrap">
        <div class="left">
          <template v-if="_detail.budgetType === 1">
            <b>
              合计总造价：<i style="color: #ff3333">¥{{ _detail.budgetTotlalMoney || "-" }}</i>
            </b>
            <span class="f12" style="color: #86909c">
              （ 空间：{{ _detail.spaceItemNum || "-" }}个 / 报价项：{{ _detail.budgetItemNum || "-" }}项）
            </span>
            comprehensiveTotal
            <span class="f12 ml20" style="color: #4e5969; display: inline-block">
              综合项金额：¥{{ _detail?.comprehensiveTotal || "-" }}
            </span>
            <span class="f12 ml20" style="color: #4e5969; display: inline-block">
              正价商品：{{ _detail.regularDiscount }}% / 特价商品：{{ _detail.specialDiscount }}%
            </span>
          </template>
          <template v-else>
            <b>
              套餐合计：<i style="color: #ff3333">¥{{ _detail.data?.budgetTotlalMoney || "-" }}</i>
            </b>
            <span class="f12" style="color: #606266">
              （套餐价：¥{{ _detail.data?.packageUnitPrice }}/㎡&nbsp;&nbsp;&nbsp;&nbsp; 可享受：¥{{
                _detail.data?.packageSquareNum
              }}/㎡ &nbsp;&nbsp;&nbsp;&nbsp;当前平方：{{ _detail.data?.houseArea }}㎡ &nbsp;&nbsp;&nbsp;&nbsp; 每多出1平方：¥{{
                _detail.data?.packageOverUnitPrice
              }}
              /㎡计算）
            </span>
            <span class="f12 ml20" style="color: #4e5969; display: inline-block">
              综合项金额：¥{{ _detail?.comprehensiveTotal || "-" }}
            </span>
            <span class="f12 ml20" style="color: #4e5969; display: inline-block">
              正价商品：{{ _detail.data?.regularDiscount }}% / 特价商品：{{ _detail.data?.specialDiscount }}%
            </span>
            <p class="f12 mt10" style="color: #86909c">
              超出{{ _detail.data?.overSquareNum || "-" }}㎡：¥{{ _detail.data?.overSquareNumMoney }} + 个性化增项/配：¥{{
                _detail.data?.customIncreaseMoney
              }}
              + 管理费：¥{{ _detail.data?.managerFee }} + 税金费：¥{{ _detail.data?.taxesFee }}
            </p>
          </template>
        </div>
      </div>
      <div class="price-wrap">
        <p class="mb6">成交金额：¥{{ _detail.data?.concludeMoney || "-" }}</p>
        <span class="f12"> 备注：{{ _detail.data?.concludeRemark || "-" }} </span>
      </div>
    </div>

    <div class="table-wrap" v-if="_detail.data?.nuclearExchangeSpaceVOS?.length > 0">
      <template v-for="(item, index) in _detail.data?.nuclearExchangeSpaceVOS || []" :key="index">
        <!-- 空间 -->
        <div class="table-item" :id="`anchor${item.spaceId}`">
          <header class="mb20">
            <div class="head-top">
              <p>
                <b class="f18">{{ item.spaceName || "--" }}</b>
                <span class="f14">
                  （合计：<i style="color: #ff3333">¥{{ item.spaceTotalMoney || "-" }}</i> ）
                </span>
              </p>
              <div class="btn-wrap">
                <slot name="headright" :obj="{ ...item, nuclearId: _detail.data.nuclearId }"></slot>
              </div>
            </div>
          </header>
          <el-table
            v-if="item?.productItemList?.length > 0"
            :data="item?.productItemList || []"
            class="jzt-table"
            border
            style="width: 100%; max-height: 400px; overflow-y: auto"
          >
            <el-table-column fixed type="index" label="序号" width="40" />
            <el-table-column fixed prop="name" label="图片" width="115">
              <template #default="scope">
                <img :src="scope.row.mainPicUrl" alt="" />
              </template>
            </el-table-column>
            <el-table-column prop="productName" label="商品名称" width="180" />
            <el-table-column prop="brandName" label="品牌" width="100" />
            <el-table-column prop="modeCode" label="型号" width="100" />
            <el-table-column prop="productUnit" label="单位" width="100">
              <template #default="scope">
                {{ useCodeArrStore().getDictName("shop_unit", scope.row.productUnit) }}
              </template>
            </el-table-column>
            <el-table-column prop="num" label="数量" width="120" />
            <el-table-column prop="actualUsedNum" label="材料用量" width="180">
              <template #default="scope">
                <!-- <el-input v-if="isEditChange" v-model="scope.row.actualUsedNum" @change="handleChangeActual(scope.row)" /> -->
                <el-input-number
                  v-if="isEditChange"
                  v-model="scope.row.actualUsedNum"
                  class="jzt-input-number jzt-input-number-hidden"
                  controls-position="right"
                  :precision="0"
                  :min="0"
                  :max="_detail.data?.showGrossProfitLimit === 1 ? 999999 : Number(scope.row.num)"
                  placeholder="请输入"
                  @change="handleChangeActual(scope.row, 3)"
                >
                </el-input-number>
                <span v-else>{{ scope.row.actualUsedNum }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="lostRate" label="耗损率" width="100" />
            <el-table-column prop="costUnitPrice" label="成本单价" width="100" />
            <el-table-column prop="productUnitPrice" label="材料单价" width="100" />
            <el-table-column prop="workerUnitPrice" label="人工费单价" width="100" />
            <el-table-column prop="unitTotalMoney" label="单项合计" width="100" />
            <el-table-column prop="actualProjectVal" label="实际工程量" width="150">
              <template #default="{ row }">
                <el-input-number
                  style="width: 100%"
                  :controls="false"
                  v-model="row.actualProjectVal"
                  :precision="0"
                  :min="0"
                  placeholder="请输入"
                  @change="handleChangeActual(row, 1, 'actualProjectVal')"
                />
              </template>
            </el-table-column>

            <el-table-column prop="projectVal" label="预算工程量" width="140">
              <template #default="{ row }">
                <!-- <el-input
                  v-if="row.isNuclear === 1 && isEditChange"
                  v-model="row.projectVal"
                  @change="handleChangeProject(row)"
                /> -->
                <span>{{ row.projectVal }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="projectTotalMoney" label="汇总合计" width="100" />
            <el-table-column prop="quotaName" label="工程项目名称" width="260" />
            <el-table-column prop="standardDesc" label="材料及工艺说明" width="140">
              <template #default="{ row }">
                <p class="text-over8" style="width: 100%" :title="row.standardDesc">
                  {{ row.standardDesc }}
                </p>
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="定额备注" width="280">
              <template #default="scope">
                <span v-html="scope.row.remark"></span>
              </template>
            </el-table-column>
            <el-table-column prop="productRemark" label="商品备注" width="280">
              <template #default="scope">
                <RemarkEditor v-model="scope.row.productRemark" :title="'修改备注'" :isEdit="false" />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
              <template #default="scope">
                <span v-if="scope.row.isNuclear === 1 && isEditChange">
                  <el-popconfirm title="确定要删除该项记录吗？" @confirm="handleDelete(scope.row)">
                    <template #reference>
                      <el-button link type="primary">删除</el-button>
                    </template>
                  </el-popconfirm>
                </span>
                <span v-else></span>
              </template>
            </el-table-column>
          </el-table>
          <el-empty v-else description="这里暂时什么都没有" />
        </div>

        <!-- 退货单 -->
        <div class="table-item">
          <header class="mb20">
            <div class="head-top">
              <p>
                <b class="f18">退货单</b
                ><span class="f14">
                  （费用合计：<i style="color: #ff3333"
                    >¥{{ item.returnOrderDetailVO?.refundBudgetTotlalMoney }}-{{
                      item.returnOrderDetailVO?.refundBudgetTotlalCNMoney
                    }}</i
                  >，管理费：¥{{ item.returnOrderDetailVO?.refundManagerFee }}+其他费用：¥{{
                    item.returnOrderDetailVO?.refundOtherFee
                  }}，综合项金额：¥{{ item.returnOrderDetailVO?.refundCustomComprehensiveFee || "-" }}，税金费：¥{{
                    item.returnOrderDetailVO?.refundTaxesFee || "-"
                  }}
                  ）
                </span>
              </p>
            </div>
          </header>
          <template v-if="item.returnOrderDetailVO?.itemList?.length > 0">
            <el-table
              :data="item.returnOrderDetailVO?.itemList || []"
              class="jzt-table"
              border
              style="width: 100%; max-height: 400px; overflow-y: auto"
              :span-method="temp => tableArraySpan(item.returnOrderDetailVO?.itemList || [], index, temp)"
            >
              <el-table-column fixed type="index" label="序号" width="40" />
              <el-table-column fixed prop="name" label="图片" width="115" class="img">
                <template #default="scope">
                  <div class="img">
                    <img :src="scope.row.mainPicUrl" alt="" />
                    <img class="icon" v-if="scope.row.barterType === 1" :src="tui" alt="" />
                    <img class="icon" v-if="scope.row.barterType === 2" :src="huan" alt="" />
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="productName" label="商品名称" width="180" />
              <el-table-column prop="brandName" label="品牌" width="100" />
              <el-table-column prop="modeCode" label="型号" width="100" />
              <el-table-column prop="productUnit" label="单位" width="100">
                <template #default="scope">
                  {{ useCodeArrStore().getDictName("shop_unit", scope.row.productUnit) }}
                </template>
              </el-table-column>
              <el-table-column prop="num" label="数量" width="100" />
              <el-table-column prop="actualUsedNum" label="实际退/换/补数量" width="180">
                <template #default="scope">
                  <!-- <el-input v-if="isEditChange" v-model="scope.row.actualUsedNum" /> -->
                  <el-input-number
                    v-if="isEditChange"
                    v-model="scope.row.actualUsedNum"
                    class="jzt-input-number jzt-input-number-hidden"
                    controls-position="right"
                    :precision="0"
                    :min="0"
                    :max="Number(scope.row.num)"
                    placeholder="请输入"
                    @change="handleChangeActual(scope.row, 1)"
                  >
                  </el-input-number>
                  <span v-else>{{ scope.row.actualUsedNum }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="lostRate" label="耗损率" width="100" />
              <el-table-column prop="costUnitPrice" label="成本单价" width="100" />
              <el-table-column prop="productUnitPrice" label="材料单价" width="100" />
              <el-table-column prop="workerUnitPrice" label="人工费单价" width="100" />
              <el-table-column prop="unitTotalMoney" label="单项合计" width="100" />
              <el-table-column prop="projectVal" label="预算工程量" width="140" />
              <el-table-column prop="projectTotalMoney" label="汇总合计" width="100" />
              <el-table-column prop="quotaName" label="工程项目名称" width="260" />
              <el-table-column prop="standardDesc" label="材料及工艺说明" width="140">
                <template #default="{ row }">
                  <p class="text-over8" style="width: 100%" :title="row.standardDesc">
                    {{ row.standardDesc }}
                  </p>
                </template>
              </el-table-column>
              <el-table-column prop="exchangeAmount" label="变更金额" width="280" />
              <el-table-column prop="exchangeCause" label="变更原因" width="280" />
            </el-table>
          </template>
          <el-empty v-else description="这里暂时什么都没有" />
        </div>

        <!-- 换补单 -->
        <div class="table-item">
          <header class="mb20">
            <div class="head-top">
              <p>
                <b class="f18">换补单</b
                ><span class="f14">
                  （费用合计：<i style="color: #ff3333"
                    >¥{{ item.replacementOrderDetailVO?.budgetTotlalMoney }}-{{
                      item.replacementOrderDetailVO?.budgetTotlalCNMoney
                    }}</i
                  >，管理费：¥{{ item.replacementOrderDetailVO?.managerFee }}+其他费用：¥{{
                    item.replacementOrderDetailVO?.otherFee
                  }}，综合项金额：¥{{ item.replacementOrderDetailVO?.customComprehensiveFee || "-" }} ，税金费：¥{{
                    item.replacementOrderDetailVO?.taxesFee || "-"
                  }}
                  ）
                </span>
                <span class="f12 ml30" style="color: #4e5969; display: inline-block"
                  >正价商品：{{ item.replacementOrderDetailVO?.regularDiscount }}% &nbsp;/&nbsp; 特价商品：{{
                    item.replacementOrderDetailVO?.specialDiscount
                  }}%</span
                >
              </p>
            </div>
          </header>

          <template v-if="item.replacementOrderDetailVO?.itemList?.length > 0">
            <el-table
              :data="item.replacementOrderDetailVO?.itemList || []"
              class="jzt-table"
              border
              style="width: 100%; max-height: 400px; overflow-y: auto"
              :span-method="temp => tableArraySpan(item.replacementOrderDetailVO?.itemList || [], index, temp)"
            >
              <el-table-column fixed type="index" label="序号" width="40" />
              <el-table-column fixed prop="name" label="图片" width="115">
                <template #default="scope">
                  <div class="img">
                    <img :src="scope.row.mainPicUrl" alt="" />
                    <img class="icon" v-if="scope.row.replenishType === 1" :src="huan" alt="" />
                    <img class="icon" v-if="scope.row.replenishType === 2" :src="bu" alt="" />
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="productName" label="商品名称" width="180" />
              <el-table-column prop="brandName" label="品牌" width="100" />
              <el-table-column prop="modeCode" label="型号" width="100" />
              <el-table-column prop="productUnit" label="单位" width="100">
                <template #default="scope">
                  {{ useCodeArrStore().getDictName("shop_unit", scope.row.productUnit) }}
                </template>
              </el-table-column>
              <el-table-column prop="num" label="数量" width="100" />
              <el-table-column prop="actualUsedNum" label="实际退/换/补数量" width="180">
                <template #default="scope">
                  <!-- <el-input v-if="isEditChange" v-model="scope.row.actualUsedNum" /> -->
                  <el-input-number
                    v-if="isEditChange"
                    v-model="scope.row.actualUsedNum"
                    class="jzt-input-number jzt-input-number-hidden"
                    controls-position="right"
                    :precision="0"
                    :min="0"
                    :max="999999"
                    placeholder="请输入"
                    @change="handleChangeActual(scope.row, 2)"
                  >
                  </el-input-number>
                  <span v-else>{{ scope.row.actualUsedNum }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="lostRate" label="耗损率" width="100" />
              <el-table-column prop="costUnitPrice" label="成本单价" width="100" />
              <el-table-column prop="productUnitPrice" label="材料单价" width="100" />
              <el-table-column prop="workerUnitPrice" label="人工费单价" width="100" />
              <el-table-column prop="unitTotalMoney" label="单项合计" width="100" />
              <el-table-column prop="actualProjectVal" label="实际工程量" width="150">
                <template #default="{ row }">
                  <el-input-number
                    style="width: 100%"
                    :controls="false"
                    v-model="row.actualProjectVal"
                    :precision="0"
                    :min="0"
                    placeholder="请输入"
                    @change="handleChangeActual(row, null, 'actualProjectVal')"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="projectVal" label="预算工程量" width="140" />
              <el-table-column prop="projectTotalMoney" label="汇总合计" width="100" />
              <el-table-column prop="quotaName" label="工程项目名称" width="260" />
              <el-table-column prop="standardDesc" label="材料及工艺说明" width="140">
                <template #default="{ row }">
                  <p class="text-over8" style="width: 100%" :title="row.standardDesc">
                    {{ row.standardDesc }}
                  </p>
                </template>
              </el-table-column>
              <el-table-column prop="exchangeAmount" label="变更金额" width="280" />
              <el-table-column prop="exchangeCause" label="变更原因" width="280" />
            </el-table>
            <!-- 底部的备注说明 -->
            <div class="tips mt14 mb14">
              <span class="label">备注说明</span>
              <!-- <el-input v-model="item.remark" disabled style="width: 100%" :rows="2" type="textarea" placeholder="" /> -->
              <RemarkEditor v-model="item.remark" :isEdit="false" />
            </div>
          </template>
          <el-empty v-else description="这里暂时什么都没有" />
        </div>

        <div class="block" v-if="index < _detail.data?.nuclearExchangeSpaceVOS?.length - 1"></div>
      </template>
    </div>
    <div v-else class="table-wrap">
      <el-empty description="这里暂时什么都没有"></el-empty>
    </div>
    <!-- 删除 二次确认 -->
    <ActionSubmitDialog
      v-model:isOpen="_isOpenDel"
      :title="'提醒'"
      :message="'您正在删除工程项目，请问是否继续当前操作？'"
      :submitBtnText="'继续'"
      @submit="returnSubmitDel"
    />
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, nextTick } from "vue";
import { ElMessage } from "element-plus";
import {
  getFolder,
  _debounce //防抖，多次频繁触发时，只执行最后一次
} from "@/utils/index";
import { WarningFilled } from "@element-plus/icons-vue";
import tui from "@/assets/images/quantity/tui.png";
import huan from "@/assets/images/quantity/huan.png";
import bu from "@/assets/images/quantity/bu.png";
import ActionSubmitDialog from "@/components/ActionSubmitDialog";
import useCodeArrStore from "@/store/modules/select";
import RemarkEditor from "@/components/RemarkEditor";
import { useRoute, useRouter } from "vue-router";

const route = useRoute();

const emit = defineEmits(["update:isOpen", "submitOk"]);
const props = defineProps({
  isOpen: {
    type: Boolean,
    default: false
  },
  optionInfo: {
    type: Object,
    default: () => {
      return {
        data: {}
      };
    }
  },
  handleChangeActual: {
    type: Function,
    default: null
  },
  handleChangeProject: {
    type: Function,
    default: null
  },
  handleDelete: {
    type: Function,
    default: null
  }
});
const isEditChange = ref(true); //变更核量单是否可编辑  query.status：1-待核量 3-已拒绝，可以直接编辑
const _isOpenDel = ref(false);
const currRow = ref({}); //点击删除的行
const textarea = ref("");
const _detail = ref({});

const _isOpen = computed({
  get() {
    return props.isOpen;
  },
  set(value) {
    emit("update:isOpen", value);
  }
});

watch(
  () => props.optionInfo,
  val => {
    _detail.value = { ...val };
    isEditChange.value = [1, 3].includes(val.data?.status) ? true : false;
    checkIsEdit();
    console.log("传递过来的变更单数据===", _detail.value);
  },
  { deep: true }
);

onMounted(() => {});

//检测路由是否存在readOnly，如果存在，整个详情页面为只读状态
const checkIsEdit = () => {
  const _readOnly = route.query.readOnly;
  if (_readOnly === "1") {
    isEditChange.value = false;
  }
};

let contentIdList = [];
const tableArraySpan = (table, nouse, { row, rowIndex, columnIndex }) => {
  let span;
  if (!table) return;

  let arr = [13, 14, 15, 16, 17];

  if (arr.indexOf(columnIndex) > -1) {
    if (!row.contentId) return;
    if (contentIdList[columnIndex] === row.contentId) span = [0, 1];
    else {
      contentIdList[columnIndex] = row.contentId;
      const rows = table.filter(item => {
        return item.contentId === contentIdList[columnIndex];
      });
      const count = rows.length;
      if (count > 1) {
        span = [count, 1];
      }
    }

    if (rowIndex === table.length - 1) contentIdList[columnIndex] = null;

    return span;
  }
};

//exchangeType:  1 : 退货单、2：换补单，3：核量新增的定额
const handleChangeActual = (row, exchangeType, key = "actualUsedNum") => {
  props.handleChangeActual && props.handleChangeActual(row, 2, key, exchangeType);
};
const handleChangeProject = row => {
  props.handleChangeProject && props.handleChangeProject(row, 2);
};
const handleDelete = row => {
  props.handleDelete && props.handleDelete(row.id, row.type, 2);
};

/**点击删除按钮 */
const clickDel = row => {
  currRow.value = row;
  _isOpenDel.value = true;
};
/**确认删除 */
const returnSubmitDel = () => {
  console.log("要删除的行===", currRow.value);
};

const reset = () => {};

const cancelClick = () => {
  reset();
  _isOpen.value = false;
  // emit("changeAttr");
};
const confirmClick = () => {};

defineExpose({});
</script>

<style lang="scss" scoped>
.text-over8 {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 8; //控制在3行显示
  -webkit-box-orient: vertical;
}

.num-wrap {
  height: 80px;

  .icon {
    position: absolute;
    top: 0px;
    left: 0px;
    color: white;
    background-color: #d54941;
    border-radius: 0 0 4px 0;
    line-height: 20px;
    padding: 0 4px;
  }
}

.block {
  height: 20px;
  background-color: #f5f7fa;
  margin-bottom: 12px;
}

.tips {
  display: flex;

  :deep(.el-textarea.is-disabled) {
    .el-textarea__inner {
      background-color: white !important;
    }
  }

  span.label {
    width: 70px;
  }
}

.table-item {
  padding: 20px;

  header {
    .head-top {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }

  :deep(.el-table__cell) {
    position: relative;
  }

  :deep(.cell) {
    overflow: visible !important;

    .img {
      .icon {
        position: absolute;
        width: 28px;
        height: auto;
        left: 0px;
        top: 0px;
      }
    }
  }

  img {
    width: 80px;
    border-radius: 4px;
  }
}

.el-button--primary.is-link.underline {
  border-radius: 0;
  border-bottom: 1px solid #213270;
}

.status-info {
  padding: 0 20px;
  height: 40px;
  display: flex;
  align-items: center;
  background-color: #f6f8fa;

  &.red {
    background-color: #ffd8d2;

    .el-icon {
      color: #ff3333;
      font-size: 18px;
    }
  }

  &.orange {
    background-color: #ffd9c2;

    .el-icon {
      color: #ff9900;
      font-size: 18px;
    }
  }

  &.green {
    background-color: #c6f3d7;

    .el-icon {
      color: #2ba471;
      font-size: 18px;
    }
  }
}

.top {
  padding: 0 20px 20px 20px;

  .total-wrap {
    display: flex;
    justify-content: space-between;

    .left {
      font-size: 16px;
      color: #606266;

      i {
        font-style: normal;
      }
    }

    .right {
      display: flex;
      justify-content: space-between;
    }
  }

  .price-wrap {
    padding: 14px 20px;
    background-color: #f6f8fa;
    margin-top: 10px;
    border-radius: 4px;

    p {
      color: #606266;
    }

    span {
      color: #86909c;
    }
  }
}

:deep(.el-tabs__nav-scroll) {
  padding-left: 20px;
}
</style>
